package com.sinoyd.itszyw.Activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.TextView;

import com.sinoyd.itszyw.Adapter.MaintainRepairsAdapter;
import com.sinoyd.itszyw.Model.RepairsInfo;
import com.sinoyd.itszyw.R;
import com.sinoyd.itszyw.View.WaterDropListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.ex.DbException;
import org.xutils.http.HttpMethod;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.List;

import static com.sinoyd.itszyw.MyApplication.GetAllUser;
import static com.sinoyd.itszyw.MyApplication.db;

/**
 * @createBy : Sinoyd 大饼洲
 * @description :
 * @projectName : ITYW
 * @creationDate: 2017-04-14 16:19
 */
@ContentView(R.layout.activity_task_repairs)
public class MaintainTaskRepairsActivity extends BaseActivity implements WaterDropListView.IWaterDropListViewListener, AdapterView.OnItemClickListener, TextView.OnEditorActionListener {

    @ViewInject(R.id.waterdrop_listview)
    private WaterDropListView mListView;
    @ViewInject(R.id.task_repairs)
    private EditText task_repairs;
    @ViewInject(R.id.txt_title)
    private TextView txt_title;

    private MaintainRepairsAdapter mAdapter;
    private List<RepairsInfo> repairsList = new ArrayList<>();
    private List<RepairsInfo> list = new ArrayList();
    private int pageSize = 20;
    private int pageCount = 0;
    private int currentPage = 0;
    private int lastPageCount = 0;
    private static int GET_REPAIRS = 555;

    private int REFRESH_FLAG = 0;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        txt_title.setText("选择查询");
        try {
            list = db.findAll(RepairsInfo.class);
        } catch (DbException e) {
            e.printStackTrace();
        }

        initData();
        task_repairs.setOnEditorActionListener(this);


    }

    private void initData() {



        currentPage = 0;
        pageCount = 1 + list.size() / pageSize;
        lastPageCount = list.size() % pageSize;
        if (list.size() == 0) {
            showToast("当前无报修人员");
        } else {
            if (pageCount > 1) {
                for (int i = 0; i < pageSize; i++) {
                    repairsList.add(list.get(i));
                }
            } else {
                for (int i = 0; i < lastPageCount; i++) {
                    repairsList.add(list.get(i));
                }
            }


        }


        mAdapter = new MaintainRepairsAdapter(this, repairsList);
        mListView.setAdapter(mAdapter);
        mListView.setWaterDropListViewListener(this);
        mListView.setPullLoadEnable(true);
        mListView.setOnItemClickListener(this);


    }
    private void getData() {
        RequestParams params = new RequestParams(GetAllUser);
        params.addBodyParameter("validation", "sinoyd123!@#");
        try {
            sendHttpRequest(params, HttpMethod.POST, GET_REPAIRS);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void httpOnSuccess(String responseStr, int requestCode) {
        if(requestCode == GET_REPAIRS){
            try {
                list.clear();
                repairsList.clear();
                JSONObject object = new JSONObject(responseStr);
                if (object.getBoolean("IsSuccess")) {
                    JSONArray array = object.getJSONArray("Data");
                    for (int i = 0; i < array.length(); i++) {
                        RepairsInfo repairsInfo = new RepairsInfo();
                        try {
                            repairsInfo.ParseRepairsInfo(array.getJSONObject(i));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        list.add(repairsInfo);
                    }
                    initData();
                    try {
                        db.dropTable(RepairsInfo.class);
                        db.save(list);
                    } catch (DbException e) {
                        e.printStackTrace();
                    }
                    if (REFRESH_FLAG == 1) {
                        mListView.stopRefresh();
                        showToast("刷新成功");
                    }

                } else {

                    showToast("获取报修人失败!");
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onRefresh() {
        REFRESH_FLAG = 1;

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {

               getData();

            }
        },1000);



    }

    @Override
    public void onLoadMore() {

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {

                ++currentPage;
                if (currentPage + 1 == pageCount) {
                    for (int i = currentPage * pageSize; i < currentPage * pageSize + lastPageCount; i++) {
                        repairsList.add(list.get(i));
                    }
                } else if (currentPage + 1 < pageCount) {
                    for (int i = currentPage * pageSize; i < currentPage * pageSize + pageSize; i++) {
                        repairsList.add(list.get(i));
                    }
                } else {
                    currentPage = pageCount - 1;
                    showToast("暂无更多数据");
                }

                mAdapter.notifyDataSetChanged();
                mListView.stopLoadMore();
            }
        },1000);

    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        Intent intent = getIntent();
        intent.putExtra("repairs",repairsList.get(position - 1));
        setResult(RESULT_OK,intent);
        finish();
    }

    private void getSelector() {
        repairsList.clear();
        list.clear();

//        if (!(stateStr.equals("所有"))) {
//            if (stateStr.equals("已提交")) {
//                builder.and("task_state", "=", "2");
//            } else {
//                builder.and("task_state", "=", "0").or("task_state", "=", "1");
//            }
//        }


        try {

            list.addAll(db.selector(RepairsInfo.class)
                    .where("repairs_name", "like", "%" + task_repairs.getText().toString() + "%")
                    .findAll());
            initData();
        } catch (DbException e) {
            e.printStackTrace();
        }

    }



    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            getSelector();
        }

        return false;
    }
}
